package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"zk2user/models"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() { //注册接口
	var err error

	account := c.GetString("account")
	password := c.GetString("password")

	if account == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "账号或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Account:  account,
		Password: password,
	}

	if err = user.GetAccountByAccount(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if user.ID > 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "账号已存在",
		}
		c.ServeJSON()
		return
	}

	if err = user.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "注册失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "注册成功",
	}
	c.ServeJSON()

}
func (c *UserController) Login() {
	var err error

	account := c.GetString("account")
	password := c.GetString("password")

	if account == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "账号或密码不能为空",
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Account:  account,
		Password: password,
	}

	if err = user.GetAccountByAccount(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "账号不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != password {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "密码错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "登陆成功",
	}
	c.ServeJSON()
	return
}
